#include "graberclass.h"

#include <QScreen>
#include <QApplication>
#include <QWindow>
#include <QDesktopWidget>
#include <QDebug>
#include <QBuffer>
#include <QSize>

GraberClass *GraberClass::GraberClassPointer = nullptr;
//新连接
bool flag_newConect = false ;
//发送数
quint16 tileNum = 0;
GraberClass::GraberClass(QObject *parent) : QObject(parent),
    m_grabTimer(Q_NULLPTR),
    m_heartbeatTimer(Q_NULLPTR),
    m_grabInterval(40),
    m_heartbeatInterval(1000*20),
    m_screenNumber(0),
    flag_start_screenshot(false),
    m_currentTileNum(0),
    m_receivedTileNum(0),
    m_permitCounter(0)

{
    GraberClassPointer  = this ;
}

int GraberClass::screen_size_change(int width, int height, int bitcount, void* param)
{
    printf("**** Screen Size Change.\n");
    return 0;
}
//重置接收数
void GraberClass::setReceivedNum(quint16 num)
{
    m_permitCounter = 0;
    m_receivedTileNum = num;
}
//是否允许发送图片
bool GraberClass::isSendPermit()
{
    bool result = false;

    if(m_currentTileNum <= (m_receivedTileNum))
        result = true;

    if(!result)
    {
        ++m_permitCounter;

        if(m_permitCounter > 20)
        {
            m_permitCounter = 0;
            result = true;
        }
    }
    qDebug()<<result ;
    return result;
}

int GraberClass::frame_callback(dp_frame_t* frame)
{
    //    if(!GraberClassPointer->isSendPermit())
    //        return 0;
    //    //发送数
    //    GraberClassPointer->m_currentTileNum = tileNum;
    //    tileNum++;
    //    if(tileNum == 25){
    //       tileNum = 0 ;
    //    }
    if(flag_newConect)
    {
        flag_newConect = false ;
        QImage newImage((uchar*)frame->buffer,(frame->cx),(frame->cy),QImage::Format_ARGB32);
        emit GraberClassPointer->imageParameters(newImage.size());
        emit GraberClassPointer->originalImage(0,0,newImage,tileNum);
    }
    if (frame->rc_array && frame->rc_count > 0) {
        QImage newImage((uchar*)frame->buffer,(frame->cx),(frame->cy),QImage::Format_ARGB32);
        int cx = frame->rc_array->rc.left ;
        int cy = frame->rc_array->rc.top ;
        int cx2 = frame->rc_array->rc.right ;
        int cy2 = frame->rc_array->rc.bottom ;
        for(int i=0;i<frame->rc_count ;i++){
            dp_rect_t* temp = frame->rc_array;
            int x = temp->rc.left;
            int y = temp->rc.top ;
            int x2 = temp->rc.right ;
            int y2 = temp->rc.bottom ;
            if(x < cx){
                cx = x ;
            }
            if(y < cy ){
                cy = y ;
            }
            if(x2 > cx2){
                cx2 = x2 ;
            }
            if(y2 > cy2 ){
                cy2 = y2 ;
            }
            frame->rc_array++;
        }
        GraberClassPointer->image = newImage.copy(cx,cy,cx2-cx,cy2-cy);
        emit GraberClassPointer->originalImage(cx,cy,GraberClassPointer->image,tileNum);
    }
    return 0;
}
void GraberClass::newSoFlash(){
    flag_newConect = true ;
}
void GraberClass::start()
{
#ifdef Q_OS_UNIX
    if(!m_grabTimer)
    {
        m_grabTimer = new QTimer(this);
        connect(m_grabTimer,SIGNAL(timeout()),this,SLOT(updateImage()));
    }
#endif
    if(!m_heartbeatTimer)
    {
        m_heartbeatTimer = new QTimer(this);
        connect(m_heartbeatTimer,SIGNAL(timeout()),this,SLOT(heartBeat()));
    }
    if(m_heartbeatTimer)
        if(!m_heartbeatTimer->isActive())
            m_heartbeatTimer->start(m_heartbeatInterval);
}

void GraberClass::stop()
{
    if(m_heartbeatTimer)
        if(m_heartbeatTimer->isActive())
            m_heartbeatTimer->stop();
#ifdef Q_OS_UNIX
    stopSending();
#endif
    emit finished();
}

void GraberClass::changeScreenNum()
{
#ifdef Q_OS_UNIX
    QList<QScreen *> screens = QApplication::screens();

    if(screens.size() > m_screenNumber+1)
        ++m_screenNumber;
    else m_screenNumber = 0;

    QScreen* screen = screens.at(m_screenNumber);
    emit screenPositionChanged(QPoint(screen->geometry().x(),screen->geometry().y()));
    startSending();
#endif
}

void GraberClass::startSending()
{
    qDebug()<<"GraberClass::startSending";
    flag_newConect = true ;
    if(!flag_start_screenshot){
        ct.grab_type = 0; ///自动选择合适的抓屏办法
        ct.display_change = screen_size_change; //屏幕尺寸改变
        ct.frame = frame_callback; //每帧回调函数
        handle = dp_create(&ct);
        dp_grab_interval(handle, m_grabInterval); ///设置40毫米间隔，也就是每秒25帧速度抓屏
        flag_start_screenshot = true ;
    }

#ifdef Q_OS_UNIX
    if(m_grabTimer)
        if(!m_grabTimer->isActive())
            m_grabTimer->start(m_grabInterval);

    updateImage();
#endif
}

void GraberClass::stopSending()
{  
    if(flag_start_screenshot){
        qDebug()<<"GraberClass::stopSending";
        ///对应镜像驱动，退出时候，需要调用 dp_destroy，否则没卸载镜像驱动的话，影响其他3D加速程序
        dp_destroy(handle);
        flag_start_screenshot = false ;
    }
#ifdef Q_OS_UNIX
    if(m_grabTimer)
        if(m_grabTimer->isActive())
            m_grabTimer->stop();
    m_first = true;
#endif
}
//心跳
void GraberClass::heartBeat(){
    emit heartBeatTimeOut();
}
void GraberClass::updateImage()
{
#ifdef Q_OS_UNIX
    QScreen *screen = QApplication::screens().at(m_screenNumber);
    QImage currentImage = screen->grabWindow(0).toImage().convertToFormat(QImage::Format_ARGB32);

    if(m_first)
    {
        m_first = false ;
        emit imageParameters(currentImage.size(), 500);
    }

    emit originalImage(0,0,currentImage,1);
#endif
}





